package com.imooc.business.core.executor.calculate;

import com.imooc.business.domain.Calculate;
import com.imooc.module.collect.enums.FunctionEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
public class ExpressionParser {

    public static String parse(Calculate calculate) {
        String expression = calculate.getExpression();
        //优先使用expression运算规则
        if (StringUtils.isNotEmpty(expression)) {
            return expression;
        }
        FunctionEnum func = FunctionEnum.parse(calculate.getFunc());
        List<String> parameters = calculate.getParameters();
        if (FunctionEnum.AVG.equals(func)) {
            /**
             * 如果是求平均，比如有 a,b,c三个参数，那么就可以将表达式
             * 设置为 (a+b+c)/count
             */
            String sumSymbol = parameters.stream().collect(Collectors.joining(FunctionEnum.SUM.getSymbol()));
            return "("+ sumSymbol +")" + func.getSymbol();
        }
        return parameters.stream().collect(Collectors.joining(func.getSymbol()));
    }
}
